package priv.conceit.sc.hoxton.file.auth;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import priv.conceit.sc.hoxton.common.web.security.WebUserDetail;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * sc.hoxton
 *
 * @author Conceit
 * 2019/9/20 增加方法
 * @since 1.0.0, 2019/9/20
 */
@Slf4j
@Component
public class TokenFilter extends OncePerRequestFilter {

	private static final String ACTUATOR="actuator";

	@Resource
	private UserDetailsService webUserDetailServiceImpl;


	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String requestURI = request.getRequestURL().toString();

		String requestToken = request.getHeader("token");
		if (StrUtil.isNotBlank(requestToken)) {
			WebUserDetail webUserDetail = (WebUserDetail) this.webUserDetailServiceImpl.loadUserByUsername(requestToken);
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(webUserDetail, null, webUserDetail.getAuthorities());
			WebAuthenticationDetailsSource webAuthenticationDetailsSource = new WebAuthenticationDetailsSource();
			WebAuthenticationDetails webAuthenticationDetails = webAuthenticationDetailsSource.buildDetails(request);
			authentication.setDetails(webAuthenticationDetails);

			SecurityContextHolder.getContext().setAuthentication(authentication);
		}

		filterChain.doFilter(request, response);
	}


}
